from django.shortcuts import render,redirect
from django.db.models import Sum,Count
from django.http import HttpResponse
from django.views.generic import ListView
from article.models import Article

from .models import Course



def CourseList(request):
    courses_list = Course.objects.all().annotate(views_count=Sum('article__counter')).annotate(articles_count=Count('article'))
    # print("courses_list:",courses_list)

    return {"courses_list":courses_list}

def CourseListView(request):

    return render(request,'course/course_list.html')

# class CourseListView(ListView):
#     """
#     教程列表
#     """
#     template_name = 'course/course_list.html'
#     context_object_name = 'courses_list'
#     model = Course
#
#     def get_queryset(self):
#         queryset = super(CourseListView,self).get_queryset()
#         queryset = queryset.annotate(views_count=Sum('article__counter')).annotate(articles_count=Count('article'))
#         return queryset



def course_articles_list(request,id):
    """
    教程中courese_sequence最小的博文
    """
    try:

        # article = Course.objects.get(pk=id).article__course.order_by('course_sequence')[0]
        course_article_list = Course.objects.get(pk=id).article_set.order_by('course_sequence')
        course = Course.objects.get(pk=id).increase_views()


        article = course_article_list[0]
        # print(article)
        # article = Course.objects.filter(article__course_id=id).values('article')
        # print("article_toc:",article.toc)
        return render(request,"course/course_article_list.html",{"article":article,"course_article_list":course_article_list})
    except Exception as e:
        # print(e)
        return render(request,"course/course_404.html")


